/** 
  *@CopyRight(c)2009 company Co.Ltd. 
  *@All right reserved.
  *@module name: App.Base.SystemManage.SystemUsersManage
  *@description:
  *
  *@author: lugj
  *@version: 1.0
  *@date: 2009/07/18
  *@last date: 2009/07/18
  *@history:
    1.
    2.
  *@bugs:
    1. 
    2. 
  *
*/ 

Ext.namespace("App.Base.SystemManage");

//SystemUsersManage Class
//config: {id: , }
App.Base.SystemManage.SystemUsersManage = function(config){
	this.config = config;
	this.MODULE_ID = App.Base.Common.func.generateGlobalUniqueId(this.config, 'SYSUSERMGR');

	this.opCmd = App.Base.common.param.OP_CMD_NONE;
	this.queryCmd = App.Base.common.param.OP_CMD_QUERY;

	this.waitOpLoadMask = new Ext.LoadMask(Ext.getBody(), {msg: "系统正在处理客户端请求，请稍候...", removeMask: false});

	//
	this.handlerReqSuccess = function(response){
		this.waitOpLoadMask.hide();
		//var result = decodeURIComponent(response.responseText);
		var result = Ext.decode(response.responseText);
		//{returnCode: , msg: );
		
		App.Base.Common.func.MESSAGEBOX_SHOW({
			title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
			//msg: result.returnCode + '：'+ result.msg,
			msg: result.msg,
			icon: (result.returnCode == App.Base.common.param.REQ_SUCCESS) ? Ext.MessageBox.INFO:Ext.MessageBox.ERROR
		});
		
		if (result.returnCode == App.Base.common.param.REQ_SUCCESS)
		{
			this.doLoad();
		}
		//
		this.opCmd = App.Base.common.param.OP_CMD_NONE;
	};

	this.handlerReqFailure = function(){
		this.waitOpLoadMask.hide();
		App.Base.Common.func.MESSAGEBOX_SHOW({
			title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
			msg: '服务器请求操作失败，请稍候重试',
			icon: Ext.MessageBox.ERROR
		});	
	};

	this.doRequest = function(config){
		if (config.params != null)
		{
			this.waitOpLoadMask.show();
			
			App.Base.Common.func.request({
				method: 'POST',
				url: App.Base.common.param.SYSUSERMGR_OPERATION_DATAURL,
				success: this.handlerReqSuccess,
				failure: this.handlerReqFailure,
				scope: this,
				params: config.params
			});
		}	
	};

	this.handler = function(o){
		if (o.action == App.Base.common.param.BUTTON_ACTION_NONE)
		{
			return;
		}
		var userId = '';
		var loginId = Ext.getCmp('loginId' + o.MODULE_ID).getValue();
		var loginPwd = Ext.getCmp('loginPwd' + o.MODULE_ID).getValue();
		var userTypeId = o.userTypeId;
		var userName = Ext.getCmp('userName' + o.MODULE_ID).getValue();
		var userDesc = Ext.getCmp('userDesc' + o.MODULE_ID).getValue();
		var displayRankingIndex = Ext.getCmp('displayRankingIndex' + o.MODULE_ID).getValue();
		var sysHoldFlag = Ext.getCmp('sysHoldFlag' + o.MODULE_ID).getValue();
		var state = Ext.getCmp('state' + o.MODULE_ID).getValue();

		if (this.opCmd == App.Base.common.param.OP_CMD_MODIFY)
		{
			userId = o.config.initValues.userId;
		}

		var params = 'SYS_OP_CMD=' + encodeURIComponent(this.opCmd) 
			+ '&USER_ID=' + encodeURIComponent(userId)
			+ '&LOGIN_ID=' + encodeURIComponent(loginId)
			+ '&LOGIN_PWD=' + encodeURIComponent(loginPwd)
			+ '&USER_TYPE_ID=' + encodeURIComponent(userTypeId)
			+ '&USER_NAME=' + encodeURIComponent(userName)
			+ '&USER_DESC=' + encodeURIComponent(userDesc)
			+ '&DISPLAY_RANKING_INDEX=' + encodeURIComponent(displayRankingIndex)
			+ '&SYS_HOLD_FLAG=' + encodeURIComponent(sysHoldFlag)
			+ '&STATE=' + encodeURIComponent(state);
		this.doRequest({params: params});
	};

	this.doAdd = function(){
		this.opCmd = App.Base.common.param.OP_CMD_ADD;
		new App.Base.SystemManage.SystemUsersMgrWindow({
			title: '新增系统用户信息',
			iconCls: 'x-menu-systemmanage-roleadd',
			opCmd: this.opCmd,
			handler: this.handler,
			scope: this
		}).getMainPanel().show();
	};

	this.doModify = function(){
		if(!this.grid.selModel.hasSelection()) 
		{
			App.Base.Common.func.MESSAGEBOX_SHOW({
				title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
				msg: '请选项修改的系统用户',
				icon: Ext.MessageBox.ERROR
			});	
			return;
		}

		this.opCmd = App.Base.common.param.OP_CMD_MODIFY;
		var record = this.grid.getSelectionModel().getSelections()[0];

		new App.Base.SystemManage.SystemUsersMgrWindow({
			title: '修改系统用户信息',
			iconCls: 'x-menu-systemmanage-rolemodify',
			opCmd: this.opCmd,
			initValues: {
				userId: record.get('userId'),
				loginId: record.get('loginId'),
				userTypeId: record.get('userTypeId'),
				userTypeName: record.get('userTypeName'),
				userName: record.get('userName'),
				userDesc: record.get('userDesc'),
				displayRankingIndex: record.get('displayRankingIndex'),
				sysHoldFlag: record.get('sysHoldFlag'),
				state: record.get('state')
			},
			handler: this.handler,
			scope: this
		}).getMainPanel().show();
	};

	this.doDelete = function(){
		if(!this.grid.selModel.hasSelection()) 
		{
			App.Base.Common.func.MESSAGEBOX_SHOW({
				title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
				msg: '请选项删除的系统用户',
				icon: Ext.MessageBox.ERROR
			});
			return;
		}

		Ext.MessageBox.show({
			title: App.Base.common.param.OA_SYSTEM_MESSAGEBOX_TIPS,
			msg: '确定要删除选定的系统用户',
			buttons: Ext.MessageBox.YESNO,
			icon: Ext.MessageBox.QUESTION,
			fn: function(btn){
				if (btn == 'yes')
				{
					this.opCmd = App.Base.common.param.OP_CMD_DELETE;
					var records = this.grid.getSelectionModel().getSelections();
					var userIds = "";
					var length = records.length;
					for (var count = 0; count < length; count++)
					{
						userIds += records[count].get("userId");
						if (count < length - 1)
						{
							userIds += App.Base.common.param.SPLIT_CHARS_VERTICAL_LINE;
						}
					}

					var params = 'SYS_OP_CMD=' + encodeURIComponent(this.opCmd) 
						+ '&USER_ID=' + encodeURIComponent(userIds);
					this.doRequest({params: params});
				}
			},
			scope: this
		});
	};

	this.doQuery = function(){
		this.queryCmd = App.Base.common.param.OP_CMD_QUERY;
		this.store.load({params:{start: 0, limit: Ext.getCmp('pgtbl' + this.MODULE_ID).pageSize}});
	};

	this.doLoad = this.doQuery;

	this.doReset = function(){
		Ext.getCmp('wantedLoginId' + this.MODULE_ID).setValue('');
		Ext.getCmp('wantedUserName' + this.MODULE_ID).setValue('');
		Ext.getCmp('wantedState' + this.MODULE_ID).setValue('-1');
	};

	//
    this.store = new Ext.data.Store({
		id: 'store' + this.MODULE_ID,
        proxy: new Ext.data.HttpProxy({url: App.Base.common.param.SYSUSERMGR_GRID_DATAURL}),
        reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
        }, [
            {name: 'userId'},
            {name: 'loginId'},
            {name: 'userName'},
            {name: 'userDesc'},           
			{name: 'userTypeId'},
            {name: 'userTypeName'},
            {name: 'lastLoginIp'},
            {name: 'lastLoginTime'},
            {name: 'lastPwdModifyTime'},
            {name: 'displayRankingIndex'},
            {name: 'sysHoldFlag'},
            {name: 'state'}
        ]),
		listeners: {
			beforeload: function(store, options){
				if ((typeof this.loginId)== "undefined")
				{
					this.loginId ='%';
					this.userName ='%';
					this.state ='%';				
				}
				else
				{
					this.loginId = Ext.getCmp('wantedLoginId' + this.MODULE_ID).getValue();
					this.userName = Ext.getCmp('wantedUserName' + this.MODULE_ID).getValue();
					this.state = Ext.getCmp('wantedState' + this.MODULE_ID).getValue();
				}

				options.params.queryCmd = encodeURIComponent(this.queryCmd);
				options.params.loginId = encodeURIComponent(this.loginId);
				options.params.userName = encodeURIComponent(this.userName);
				options.params.state = encodeURIComponent(this.state);
			},
			scope: this
		}
    });
    
	this.sm = new Ext.grid.CheckboxSelectionModel();//{handleMouseDown: Ext.emptyFn}

    this.grid = new Ext.grid.GridPanel({
		id: 'grid' + this.MODULE_ID,
    	border: false,
    	frame: true,
        stripeRows: true,
        loadMask: {msg: '系统正在加载操作用户数据，请稍候...'},
        //autoExpandColumn: '',
        enableColumnMove: false,
		enableColumnResize: false,
		//enableHdMenu: false,
        autoDestroy: true,
        //title: '操作用户信息',
		sm: this.sm,
        cm: new Ext.grid.ColumnModel([
			new Ext.grid.RowNumberer(),
            {id: 'userId' + this.MODULE_ID, header: '用户编码', dataIndex: 'userId', width: 64, hidden: true},
            {header: '登录账号', dataIndex: 'loginId' , width: 56},
            {header: '用户名称', dataIndex: 'userName' , width: 56},
            {header: '描述', dataIndex: 'userDesc' , width: 64},
            {header: '用户类型编码', dataIndex: 'userTypeId' , width: 64, hidden: true},
            {header: '用户类型名称', dataIndex: 'userTypeName' , width: 64},
            {header: '最近登录IP地址', dataIndex: 'lastLoginIp' , width: 64},
            {header: '最近登录日期', dataIndex: 'lastLoginTime' , width: 64},
            {header: '最近密码修改时间', dataIndex: 'lastPwdModifyTime' , width: 64},
            {header: '显示顺序号', dataIndex: 'displayRankingIndex' , width: 64, hidden: true},
			{header: '系统创建', dataIndex: 'sysHoldFlag' , width: 32, align: 'center', renderer: function(value){
					if (value == '1')
					{
						return "是";
					}
					else if (value == '0')
					{
						return "否";
					}
					else
					{
						return "未知";
					}
			}},
			{header: '状态', dataIndex: 'state' , width: 32, align: 'center', renderer: function(value){
				if (value == '0')
				{
					return "<font color='black'>正常</font>";
				}
				else if (value == '1')
				{
					return "<font color='green'>已冻结</font>";
				}
				else
				{
					return "<font color='red'>未知</font>";
				}
			}},
			this.sm
        ]),
        store: this.store,
        //tbar: new Ext.Toolbar(['']),
		bbar: new Ext.PagingToolbar({
			id: 'pgtbl' + this.MODULE_ID,
            pageSize: App.Base.common.param.GRID_PAGE_SIZE_10,
            store: this.store,
            displayInfo: true,
            displayMsg: '共 {2} 条',//'显示第 {0} 条到 {1} 条记录，共 {2} 条',
            emptyMsg: "没有记录",
            plugins: new Ext.ux.PageSizePlugin()
        }),
        viewConfig: {
            forceFit: true,
            enableRowBody: true,
            getRowClass: function(record, rowIndex, p, ds) {
                var cls = 'white-row';
                switch (rowIndex%2) {
                    case 1:
                        cls = 'red-row'
                        break;
                }
                return cls;
            }
        },
		listeners: {
			dblclick: function(e){
				this.doModify();
			},
			scope: this
		}
    });
    
    this.form = new Ext.FormPanel({
		//id: 'form' + this.MODULE_ID,
		autoDestroy: true,
		border: false,
		layout: 'border',
		items: [{
			region:'center',
			frame: true,
			border: false,
			autoScroll: true,
			labelAlign: 'right',
			labelWidth: 128,
			bodyStyle:'padding:5px 5px 5px 0',
			layout: 'border',
			items: [{
				region:'north',
				title : '系统用户查询',
				height: 160,
				border: false,
				frame: false,
				autoScroll: true,
				split : true,
				collapsible : true,
				bodyStyle:'padding:18px 5px 5px 0',
				layout: 'form',			
				items :[
				new Ext.Panel({
					layout:'column',
					items: [{
						width: 290,
						layout: 'form',
						items:[{
								xtype: 'textfield',
								id: 'wantedLoginId' + this.MODULE_ID,
								name: 'wantedLoginId' + this.MODULE_ID,
								fieldLabel: '<font color="red">系统用户账号</font>',
								maskRe: eval(App.Base.common.param.TEXTFIELD_INPUT_MASKRE),
								regex: eval(App.Base.common.param.TEXTFIELD_INPUT_REGEX),
								regexText: App.Base.common.param.TEXTFIELD_INPUT_REGEX_TIPS
							}
						]
					},{
						width: 320,
						layout: 'form',
						items: [{
							xtype: 'textfield',
							id: 'wantedUserName' + this.MODULE_ID,
							name: 'wantedUserName' + this.MODULE_ID,
							fieldLabel: '<font color="red">系统用户名称</font>',
							maskRe: eval(App.Base.common.param.TEXTFIELD_INPUT_MASKRE),
							regex: eval(App.Base.common.param.TEXTFIELD_INPUT_REGEX),
							regexText: App.Base.common.param.TEXTFIELD_INPUT_REGEX_TIPS
						}]
					}]
				}), 
				new Ext.Panel({
					layout:'column',
					items: [{
						width: 248,
						layout: 'form',
						items:[
							new Ext.form.ComboBox({
								id: 'wantedState' + this.MODULE_ID,
								name: 'wantedState' + this.MODULE_ID,
								fieldLabel: '<font color="red">系统用户状态</font>',
								width : 80,
								store: new Ext.data.SimpleStore({
									fields: ['value', 'text'],
									data: [
										['-1', '所有'],
										['0', '正常'],
										['1', '已冻结']
									]
								}),
								value: -1,	
								mode: 'local',
								editable: false,
								allowBlank: false,
								triggerAction: 'all',
								valueField: 'value',
								displayField: 'text'
							})
						]
					},{
						width: 86,
						items: [
							new Ext.Button({
								text: '<font color="blue">查 询</font>',
								iconCls: 'x-button-systemmanage-search',
								handler: function(){
									this.doQuery();
								},
								scope: this
							})	
						]
					},{
						width: 128,
						items: [
							new Ext.Button({
								text: '<font color="blue">重 置</font>',
								iconCls: 'x-menu-systemmenusmanage-rset',
								handler: function(){
									this.doReset();
								},
								scope: this
							})	
						]
					}]
				})
				],
				bbar: new Ext.Toolbar({
					id: 'tbar' + this.MODULE_ID ,
					border: false,
					items : ['-', {
						text:'<font color="blue">新增</font>',
						iconCls: 'x-menu-systemmanage-roleadd',
						//tooltip: {title:'Tip Title', text:'This is a an example QuickTip for a toolbar item'},
						//enableToggle: true,
						handler: function(){
							this.doAdd();
						},
						scope: this
					}, '-', {
						text:'<font color="blue">修改</font>',
						iconCls: 'x-menu-systemmanage-rolemodify',
						tooltip: {title:'提示', text:'如果选择了多个系统用户记录，则默认只修改选中的第一个记录'},
						handler: function(){
							this.doModify();
						},
						scope: this
					}, '-', {
						text:'<font color="blue">删除</font>',
						iconCls: 'x-menu-systemmanage-roledelete',
						handler: function(){
							this.doDelete();
						},
						scope: this
					}, '-']
				})
			},{
				region:'center',
				//title : '系统用户信息',
				//frame: true,
				border: false,
				autoScroll: true,
				bodyStyle:'padding:5px 5px 5px 0',
				layout: 'fit',
				items: [this.grid]		
			}]
		}]
	});

	this.doLoad();

	//this.form.doLayout();

	//defined methods.
    if((typeof App.Base.SystemManage.SystemUsersManage.SIMULATE_SHARED_METHODS_FLAG) == "undefined")
    {
        App.Base.SystemManage.SystemUsersManage.SIMULATE_SHARED_METHODS_FLAG = true;   

        App.Base.SystemManage.SystemUsersManage.prototype.getMainPanel = function(){   
            return this.form;  
        };
 
        var __ctor = function(){
        }();
    }
}